package com.blb.zy_community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.zy_community.entity.SysMenu;
import com.blb.zy_community.entity.SysRole;
import com.blb.zy_community.entity.SysUser;
import com.blb.zy_community.entity.SysUserPost;
import com.blb.zy_community.entity.SysUserRole;
import com.blb.zy_community.mapper.*;
import com.blb.zy_community.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 二组
 * @since 2023-06-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Page<SysUser> GetUserById(Long current,Long size,String userName) {
        return sysUserMapper.selectUserById(new Page<>(current,size),userName);
    }

    /**
     * 分页和模糊查询列表
     * @param page
     * @param userName
     * @param phonenumber
     * @param status
     * @param startTime
     * @return
     */
    @Override
    public Page<SysUser> SelectSysUserPage(Page<SysUser> page, String userName, String phonenumber, String status, String startTime,String endTime,Long deptId) {
        Page<SysUser> sysUserPage = sysUserMapper.SelectSysUserPage(page, userName, phonenumber, status, startTime, endTime,deptId);
        return sysUserPage;
    }

    /**
     * 根据用户名
     * @param username
     * @return
     */
    @Override
    public List<GrantedAuthority> getAuto(String username) {
        List<SysRole> roles = userMapper.selectRolesByUsername(username);
        List<SysMenu> menus = userMapper.selectPermissionByUsername(username);
        //连接到字符串中  ROLE_XXX,ROLE_XXX,XXX,XX
        StringBuffer stringBuffer = new StringBuffer();
        roles.forEach(role -> stringBuffer.append("ROLE_" + role.getRoleName() + ","));
        menus.forEach(permission -> stringBuffer.append(permission.getMenuName() + ","));
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        //如果不为空，将用户账号密码包装到UserDetails中返回 参数：账号，密码，权限
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(stringBuffer.toString());
        return  authorities;
    }


    /**
     * 新增用户信息
     * @param sysUser
     * @return
     */
    public void addUserRoleAndPost(SysUser sysUser, List<Long> postIds, List<Long> roleIds) {
        sysUserMapper.insert(sysUser);
        //获取user表中的user对象
        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, sysUser.getUserName()));
        Long userId = user.getUserId();
        //循环获取userRole表中的角色Id
        for (Object roleId:roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId((Long) roleId);
            sysUserRoleMapper.insert(userRole);
        }
        //循环获取userPost中的岗位id
        for (Object postId: postIds) {
            SysUserPost userPost = new SysUserPost();
            userPost.setUserId(userId);
            userPost.setPostId((Long) postId);
            sysUserPostMapper.insert(userPost);
        }

    }


    /**
     * 修改用户状态
     * @param statusId
     * @param userId
     */
    @Override
    public void updateStatus(Long statusId, Long userId) {
        sysUserMapper.updateStatus(statusId,userId);
    }

    /**
     * 根据id批量删除
     * @param userIds
     */
    @Override
    public void deleteSysUserIds(Long[] userIds) {
        sysUserMapper.deleteByUserIds(userIds);
    }

    /**
     * 修改
     * @param sysUser
     * @param roleIds
     * @param postIds
     */
    public void updateUserRoleAndPost(SysUser sysUser, List roleIds, List postIds) {
        sysUserPostMapper.delete(new QueryWrapper<SysUserPost>().lambda().eq(SysUserPost::getUserId,sysUser.getUserId()));
        sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId,sysUser.getUserId()));
        //循环获取userRole表中的角色Id
        for (Object roleId:roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setRoleId((Long) roleId);
            sysUserRoleMapper.insert(userRole);
        }
        //循环获取userPost中的岗位id
        for (Object postId: postIds) {
            SysUserPost userPost = new SysUserPost();
            userPost.setUserId(sysUser.getUserId());
            userPost.setPostId((Long) postId);
            sysUserPostMapper.insert(userPost);
        }
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void updatePwd(Long userId,String password) {
        sysUserMapper.updatePwd(userId,password);
    }

    @Override
    public SysUser getSysUserByUserName(String username) {
        SysUser sysUser= sysUserMapper.selectSysUserByUserName(username);
        return sysUser;
    }

    @Override
    public Page<SysUser> selectSysUserPage2(Page<Object> objectPage, String userName, String phonenumber, String status, String startTime, String endTime, Long deptId) {
        Page<SysUser> sysUserPage= sysUserMapper.selectSysUserPage2(objectPage, userName, phonenumber, status, startTime, endTime,deptId);
        return sysUserPage;
    }
}
